﻿using System;
using System.Diagnostics;
using System.Net.Http;
using System.Net.Http.Json;
using System.Text.Json;
using System.Threading.Tasks;
using ZechatApp.Models;

namespace ZechatApp.Services;

public class HttpClientService(IHttpClientFactory httpClientFactory)
{
    public async Task<BzUser?> BzAuthAsync(string username, string password)
    {
        var client = httpClientFactory.CreateClient("BzClient");

        var data = JsonContent.Create(new BzLoginReq() { Account = username, Password = password, Role = 2 });

        Console.WriteLine($"data: {data.Value}");

        try
        {
            var res = await client.PostAsync("http://kefu.shunjicangchu.com/mini/user/login", data);

            Console.WriteLine($"res: {await res.Content.ReadAsStringAsync()}");

            var response = await res.Content.ReadFromJsonAsync<BzResponse<BzLogin>>();

            Console.WriteLine($"response: {response}");
            
            var user = response.Data.Userinfo;
            
            return user;
        }
        catch (HttpRequestException ex)
        {
            Console.WriteLine($"HTTP request failed: {ex.Message}");
            throw;
        }
        catch (JsonException ex)
        {
            Console.WriteLine($"JSON deserialization failed: {ex.Message}");
            throw;
        }
    }

    public async Task<string> GetBaidu()
    {
        var client = httpClientFactory.CreateClient("BzClient");
        var res = await client.GetStringAsync("https://www.baidu.com/");
        Console.WriteLine($"res: {res}");
        return res;
    }

    public async Task<WxResponse<T>> WxPostAsync<T>(JsonContent content)
    {
        var client = httpClientFactory.CreateClient("WxClient");
        var uri = $"http://localhost:{App.SendPort}/api/";
        var sw = Stopwatch.StartNew();
        Console.WriteLine($"request content: {content.Value}");

        try
        {
            var postResponse = await client.PostAsync(uri, content);
            Console.WriteLine($"Request completed in {sw.ElapsedMilliseconds}ms");

            var response = await postResponse.Content.ReadFromJsonAsync<WxResponse<T>>();

            if (response == null)
            {
                throw new InvalidOperationException("Failed to deserialize response.");
            }

            response.Errmsg = CommonService.DecodeCNEncodeToUtf8(response.Errmsg);

            return response;
        }
        catch (HttpRequestException ex)
        {
            Console.WriteLine($"HTTP request failed: {ex.Message}");
            throw;
        }
        catch (JsonException ex)
        {
            Console.WriteLine($"JSON deserialization failed: {ex.Message}");
            throw;
        }
        finally
        {
            content?.Dispose();
        }
    }
}